package com.iptv.grape;

import androidx.appcompat.app.AppCompatActivity;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.SyncStateContract;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.iptv.grape.util.AppLog;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class MediaPlayerActivity extends BaseActivity {

    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private MediaPlayer mediaPlayer;

    private ProgressBar progressBar;
    private Button button_play;
    private Button button_replay;
    private Button button_screenShot;
    private Button button_changeVedioSize;
    private TextView vedioTiemTextView;
    private SeekBar seekbar;
    private String videoTimeString;

    String livePalyUlr1 = "http://111.7.174.11/PLTV/88888888/224/3221225899/index.m3u8?icpid=88888888&servicetype=1";

    //String livePalyUlr1="http://123.160.30.20:6610/HKVOD/32/1e7a966b4c4e20190703112341687222?ispcode=12&virtualDomain=HKVOD.vod_hpd.zte.com&IASHttpSessionId=RR35892019082105394195685650";

    @Override
    protected void onCreate(Bundle savedInstanceState) {


        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();//屏幕宽度
        int height = wm.getDefaultDisplay().getHeight();//屏幕高度

        AppLog.getCurLog().out("width--" + width);
        AppLog.getCurLog().out("height--" + height);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_player);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        // 设置surfaceHolder
        surfaceHolder = surfaceView.getHolder();
        // 设置Holder类型,该类型表示surfaceView自己不管理缓存区,虽然提示过时，但最好还是要设置

        //surfaceHolder.setFixedSize(176,144);//设置分辨率
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceHolder.setFixedSize(176, 144);//设置分辨率
        surfaceHolder.setKeepScreenOn(true);
        // 设置surface回调
        surfaceHolder.addCallback(new SurfaceCallback());
        seekbar = findViewById(R.id.seekbar);
        progressBar = findViewById(R.id.progressBar);
        button_play = findViewById(R.id.button_play);
        button_replay = findViewById(R.id.button_replay);
        button_screenShot = findViewById(R.id.button_screenShot);
        button_changeVedioSize = findViewById(R.id.button_changeVedioSize);
        vedioTiemTextView = findViewById(R.id.textView_showTime);
    }





    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 90:
                    vedioTiemTextView.setText((String)msg.obj + "/" + videoTimeString);
                    break;
            }
        }
    };


    // SurfaceView的callBack
    private class SurfaceCallback implements SurfaceHolder.Callback,
            SeekBar.OnSeekBarChangeListener,
            MediaPlayer.OnErrorListener,
            MediaPlayer.OnPreparedListener {
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // TODO Auto-generated method stub
            if (progress >= 0) {
                // 如果是用户手动拖动控件，则设置视频跳转。
                if (fromUser) {
                    mediaPlayer.seekTo(progress);
                }
                // 设置当前播放时间
                vedioTiemTextView.setText(getShowTime(progress) + "/" + videoTimeString);
            }
        }

        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            // SurfaceView的大小改变
        }

        public void surfaceCreated(SurfaceHolder holder) {
            // surfaceView被创建
            // 设置播放资源
            playVideo();
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            // surfaceView销毁
            // 如果MediaPlayer没被销毁，则销毁mediaPlayer
            if (null != mediaPlayer) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
        }

        /**
         * 播放视频
         */
        public void playVideo() {
            // 初始化MediaPlayer
            mediaPlayer = new MediaPlayer();
            // 重置mediaPaly,建议在初始滑mediaplay立即调用。
            mediaPlayer.reset();
            // 设置声音效果
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            // 设置播放完成监听
            //mediaPlayer.setOnCompletionListener(this);
            // 设置媒体加载完成以后回调函数。
            mediaPlayer.setOnPreparedListener(this);
            // 错误监听回调函数
            mediaPlayer.setOnErrorListener(this);
            // 设置缓存变化监听
            //mediaPlayer.setOnBufferingUpdateListener(this);
            Uri uri = Uri
                    .parse(MediaPlayerActivity.this.livePalyUlr1);
            try {
                // mediaPlayer.reset();

                mediaPlayer.setDataSource(MediaPlayerActivity.this.getApplicationContext(), uri);
                //mediaPlayer.setDisplay(surfaceView.getHolder());
                // 设置异步加载视频，包括两种方式 prepare()同步，prepareAsync()异步
                mediaPlayer.prepareAsync();
                //mediaPlayer.prepare();
               // mediaPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        /**
         * 视频加载完毕监听
         *
         * @param mp
         */
        @Override
        public void onPrepared(MediaPlayer mp) {
            // 当视频加载完毕以后，隐藏加载进度条
            progressBar.setVisibility(View.GONE);
            // 判断是否有保存的播放位置,防止屏幕旋转时，界面被重新构建，播放位置丢失。

            mediaPlayer.setDisplay(surfaceHolder);
            // 设置surfaceView保持在屏幕上
            mediaPlayer.setScreenOnWhilePlaying(true);

            // 毫秒
            //mediaPlayer.seekTo(415000);
            // 播放视频
            mediaPlayer.start();


            // 设置显示到屏幕

            surfaceHolder.setKeepScreenOn(true);
            // 设置控制条,放在加载完成以后设置，防止获取getDuration()错误
            MediaPlayerActivity.this.seekbar.setProgress(0);
            MediaPlayerActivity.this.seekbar.setMax(mediaPlayer.getDuration());
            AppLog.getCurLog().out(mediaPlayer.getDuration());
            // 设置播放时间
            videoTimeString = getShowTime(mediaPlayer.getDuration());

            vedioTiemTextView.setText("00:00:00/" + videoTimeString);
            // 设置拖动监听事件
            //seekBar.setOnSeekBarChangeListener(new SeekBarChangeListener());
            // 设置按钮监听事件
            // 重新播放
            //replayButton.setOnClickListener(MediaPlayerActivity.this);
            // 暂停和播放
            //playButton.setOnClickListener(MediaPlayerActivity.this);
            // 截图按钮
            //screenShotButton.setOnClickListener(MediaPlayerActivity.this);
            seekBarAutoFlag = true;
            // 开启线程 刷新进度条
            thread.start();
        }

        private boolean seekBarAutoFlag;
        /**
         * 滑动条变化线程
         */
        private Thread thread = new Thread() {

            public void run() {
                // TODO Auto-generated method stub
                super.run();
                // 增加对异常的捕获，防止在判断mediaPlayer.isPlaying的时候，报IllegalStateException异常
                try {
                    while (seekBarAutoFlag) {
                        /*
                         * mediaPlayer不为空且处于正在播放状态时，使进度条滚动。
                         * 通过指定类名的方式判断mediaPlayer防止状态发生不一致
                         */
                        Thread.sleep(800);
                        if (null != MediaPlayerActivity.this.mediaPlayer
                                && MediaPlayerActivity.this.mediaPlayer.isPlaying()) {
                            seekbar.setProgress(mediaPlayer.getCurrentPosition());
                            //String str = getShowTime(mediaPlayer.getCurrentPosition());
                            //AppLog.getCurLog().out(str + "/" + videoTimeString);
                            //vedioTiemTextView.setText(str + "/" + videoTimeString);
                            Message message = mHandler.obtainMessage(90);
                            message.obj = getShowTime(mediaPlayer.getCurrentPosition());
                            mHandler.sendMessage(message);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    AppLog.getCurLog().out(e.getMessage());
                }
            };

        };


        public String getShowTime(long milliseconds) {
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
            formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
            String hms = formatter.format(milliseconds);
            return hms;
        }

        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            AppLog.getCurLog().out("MediaPlayer---OnError - Error code: " + what + " Extra code: " + extra);
            switch (what) {
                case -1004:
                    AppLog.getCurLog().out("MEDIA_ERROR_IO");
                    break;
                case -1007:
                    AppLog.getCurLog().out("MEDIA_ERROR_MALFORMED");
                    break;
                case 200:
                    AppLog.getCurLog().out("MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK");
                    break;
                case 100:
                    AppLog.getCurLog().out("MEDIA_ERROR_SERVER_DIED");
                    break;
                case -110:
                    AppLog.getCurLog().out("MEDIA_ERROR_TIMED_OUT");
                    break;
                case 1:
                    AppLog.getCurLog().out("MEDIA_ERROR_UNKNOWN");
                    break;
                case -1010:
                    AppLog.getCurLog().out("MEDIA_ERROR_UNSUPPORTED");
                    break;
            }

            switch (extra) {
                case 800:
                    AppLog.getCurLog().out("MEDIA_INFO_BAD_INTERLEAVING");
                    break;
                case 702:
                    AppLog.getCurLog().out("MEDIA_INFO_BUFFERING_END");
                    break;
                case 701:
                    AppLog.getCurLog().out("MEDIA_INFO_METADATA_UPDATE");
                    break;
                case 802:
                    AppLog.getCurLog().out("MEDIA_INFO_METADATA_UPDATE");
                    break;
                case 801:
                    AppLog.getCurLog().out("MEDIA_INFO_NOT_SEEKABLE");
                    break;
                case 1:
                    AppLog.getCurLog().out("MEDIA_INFO_UNKNOWN");
                    break;
                case 3:
                    AppLog.getCurLog().out("MEDIA_INFO_VIDEO_RENDERING_START");
                    break;
                case 700:
                    AppLog.getCurLog().out("MEDIA_INFO_VIDEO_TRACK_LAGGING");
                    break;
            }
            return false;
        }
    }


}
